package com.ljt.controller.admin;

import com.alibaba.fastjson.JSON;
import com.ljt.entity.RoleEntity;
import com.ljt.entity.UserEntity;
import com.ljt.service.RoleService;
import com.ljt.utils.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wb-ljt251780 on 2017/7/28.
 */
@Controller
@RequestMapping("role")
public class RoleController {
    Logger logger = LoggerFactory.getLogger(RoleController.class);
    @Autowired
    private RoleService roleService;

    @RequestMapping
    public String index() {
        return "admin/role/index";
    }
    @ResponseBody
    @RequestMapping("list")
    public Object list(@RequestParam(required = false,defaultValue="1")Integer pageIndex,@RequestParam(required = false,defaultValue="15") Integer pageSize) {
        Pageable pageRequest = new PageRequest(pageIndex-1, pageSize);
        Page<RoleEntity> userEntities = roleService.findAll(pageRequest);
        return JSON.toJSON(userEntities);
    }
    @RequestMapping("edit")
    public String edit(Long id,ModelMap model) {
        if(id!=null) {
            RoleEntity roleEntity = roleService.findById(id);
            model.addAttribute("role",roleEntity);
        }else {
            model.addAttribute("role", new RoleEntity());
        }
        return "admin/role/edit";
    }
    @ResponseBody
    @RequestMapping("save")
    public ResponseData save(RoleEntity roleEntity) {
        try {
            roleService.saveOrUpdate(roleEntity);
        } catch (Exception e) {
            return ResponseData.error(e.getMessage());
        }
        return ResponseData.success();
    }
}
